package com.proxy.server.frontend.handler.request.proxy;

import com.proxy.common.constant.ErrorCodeType;
import com.proxy.common.packet.BinaryPacket;
import com.proxy.common.packet.ErrorPacket;
import com.proxy.common.packet.OkPacket;
import com.proxy.parser.result.UseParsedResult;
import com.proxy.router.SQLRouteResult;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.session.Session;

import java.nio.charset.Charset;

/**
 * Created by liufish on 16/12/29.
 */
public class SetNamesProxy {


    public static void doProxy(BinaryPacket bin, Session session, SQLRouteResult result) {

        FrontendConnection connection = session.getFrontendConnection();
        UseParsedResult useParsedResult = (UseParsedResult)result.getExtra();
        String  charset = useParsedResult.getDataBase();
        if (connection.setCharset(charset)) {
            connection.write(OkPacket.getOk(++bin.packetId));
        } else {
            ErrorPacket error = new ErrorPacket();
            error.packetId = ++bin.packetId;
            error.errNo = ErrorCodeType.ER_UNKNOWN_CHARACTER_SET;
            error.message = "Unknown charset!".getBytes(Charset.forName(charset));
            connection.write(error);
        }
    }
}
